package com.oneday.ashop.webgate.user;

import com.oneday.ashop.core.base.util.StringUtil;
import com.oneday.ashop.core.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * User:bob.yang
 * Date 2015/7/15 0015
 */
@Controller()
@RequestMapping("user")
public class UserControl {

    @Autowired
    private UserService userService;
//    private BookService bookService;

    @RequestMapping("/welcome")
    public String login() {
        return "user/login";
    }
    /**
     * 用户登陆
     * @param account
     * @param password
     * @return
     */
    @RequestMapping("login")
    public String login(String account, String password,HttpServletRequest request, Model model) {
        if(account == null || "".equals(account)) {
            model.addAttribute("account", account);
            model.addAttribute("password", password);
            model.addAttribute("code", "账号不能为空！");
            return "user/login";
        }else if(password == null || "".equals(password)){
            model.addAttribute("account", account);
            model.addAttribute("password", password);
            model.addAttribute("code", "密码不能为空！");
            return "user/login";
        }
        HttpSession session = request.getSession();
        User user = userService.login(account, password);
        if(user != null) {
            session.setMaxInactiveInterval(600); //设置session失效时间
            session.setAttribute("user", user);
//            model.addAttribute("user", user);
            return "redirect:/book/book_menu.htm";
        }else {
            model.addAttribute("account", account);
            model.addAttribute("password", password);
            model.addAttribute("code", "账号或密码错误！");
            return "user/login";
        }
    }

    /**
     * 用户退出登陆
     * @return
     */
    @RequestMapping("logout")
    public String logout(HttpServletRequest request) {
        HttpSession session = request.getSession();
        session.removeAttribute("user");
        session.invalidate();
        return "user/login";
    }

    /**
     * 获得注册页面
     * @return
     */
    @RequestMapping("get_register")
    public String getRegister() {
        return "user/register";
    }

    /**
     * 个人信息
     * @param session
     * @param model
     * @return
     */
    @RequestMapping("get_profile")
    public String getProfile( HttpSession session, Model model) {
        User user = (User)session.getAttribute("user");
        if(user == null) {
            return "user/login";
        }
        user = userService.findUser(user.getId());
        model.addAttribute("user", user);
        return "user/profile";
    }

    /**
     * 用户注册
     * @param name
     * @param email
     * @param password
     * @param city
     * @param telephone
     * @param validateCode
     * @param isPermit
     * @return
     */
    @RequestMapping("register")
    public String register(String name, String email, String password, String city, String telephone, String validateCode, String isPermit, Model model) {
        int[] result = userService.register(name, email, password, city, telephone, validateCode, isPermit);
        switch (result[0]) {
            case 1:
                model.addAttribute("name", name);
                model.addAttribute("email", email);
                model.addAttribute("password", password);
                model.addAttribute("city", city);
                model.addAttribute("telephone", telephone);
                model.addAttribute("validateCode", validateCode);
                model.addAttribute("isPermit", isPermit);
                model.addAttribute("code", "手机格式不正确！");
                return "user/register";
            case 2:
                model.addAttribute("name", name);
                model.addAttribute("email", email);
                model.addAttribute("password", password);
                model.addAttribute("city", city);
                model.addAttribute("telephone", telephone);
                model.addAttribute("validateCode", validateCode);
                model.addAttribute("isPermit", isPermit);
                model.addAttribute("code", "邮箱格式不正确！");
                return "user/register";
            case 3:
                model.addAttribute("name", name);
                model.addAttribute("email", email);
                model.addAttribute("password", password);
                model.addAttribute("city", city);
                model.addAttribute("telephone", telephone);
                model.addAttribute("validateCode", validateCode);
                model.addAttribute("isPermit", isPermit);
                model.addAttribute("code", "昵称过长！");
                return "user/register";
            case 4:
                model.addAttribute("name", name);
                model.addAttribute("email", email);
                model.addAttribute("password", password);
                model.addAttribute("city", city);
                model.addAttribute("telephone", telephone);
                model.addAttribute("validateCode", validateCode);
                model.addAttribute("isPermit", isPermit);
                model.addAttribute("code", "密码格式不正确！");
                return "user/register";
            case 5:
                model.addAttribute("name", name);
                model.addAttribute("email", email);
                model.addAttribute("password", password);
                model.addAttribute("city", city);
                model.addAttribute("telephone", telephone);
                model.addAttribute("validateCode", validateCode);
                model.addAttribute("isPermit", isPermit);
                model.addAttribute("code", "未同意协议不能注册");
                return "user/register";
            case 6:
                model.addAttribute("name", name);
                model.addAttribute("email", email);
                model.addAttribute("password", password);
                model.addAttribute("city", city);
                model.addAttribute("telephone", telephone);
                model.addAttribute("validateCode", validateCode);
                model.addAttribute("isPermit", isPermit);
                model.addAttribute("code", "验证码不正确！");
                return "user/register";
            case 7:
                model.addAttribute("name", name);
                model.addAttribute("email", email);
                model.addAttribute("password", password);
                model.addAttribute("city", city);
                model.addAttribute("telephone", telephone);
                model.addAttribute("validateCode", validateCode);
                model.addAttribute("isPermit", isPermit);
                model.addAttribute("code", "该邮箱或电话已经注册！");
                return "user/register";
            case 0:
                return "user/login";
        }
         return  "user/login";
    }

    /**
     * 网站评价
     * @param evaluation
     * @param advice
     * @param reason
     */
    @RequestMapping("web_evaluate")
    @ResponseBody
    public  String webEvaluate(Integer evaluation, String advice, String reason) {
        userService.suggest(evaluation, advice, reason);
        Map<String, String> map = new HashMap<>();
        map.put("msg", "success");
        return "msg";
    }

    @RequestMapping("addUser")
     public String addUser(@RequestParam(value = "name", required = false) String name,
                           @RequestParam(value = "password", required = false) String password,
                           @RequestParam(value = "address", required = false) String address) {
        if(name == null || password == null) {
            return "user/login";
        }
        userService.addUser(name, password, address);
        return "user/test";
    }

    @RequestMapping("showRegister")
    public String showRegister() {
        return "register";
    }


//    @RequestMapping("register")
    public String register(@RequestParam("name") String name,
                           @RequestParam("password") String password,
                           @RequestParam(value = "password2", required = false) String password2) {

        // 后台验证注册信息
//        int checkResult = userService.checkRegInfo(name, password, password2);
        int checkResult = 4;
        switch (checkResult)
        {
            case 1: // 用户信息不完整
                return "user/register";
            case 2: // 2次输入密码不匹配
                return "user/register";
            case 3: // 账号已存在
                return "user/register";
            default:
                userService.addUser(name, password);
                return "user/login";
        }
    }

    @RequestMapping(value = "checkAuthCode", method = RequestMethod.POST)
    @ResponseBody
    public String checkAuthCode(@RequestParam(value = "mailAuthCode") String mailAuthCode, HttpSession session) {
        String result;
        String rand = (String)session.getAttribute("rand");
        if (mailAuthCode.equals(rand)) {
            result = "true";
        } else {
            result = "false";
        }

        return result;
    }

    @RequestMapping(value = "queryUserByName", method = RequestMethod.POST)
    @ResponseBody
    public String queryUserByName(@RequestParam(value = "name") String name) {
        String result;
        if (userService.queryUserByName(name)) {
            result = "false";
        } else {
            result = "true";
        }

        return result;
    }


    @RequestMapping("updateUser")
    public String updateUser(@RequestParam(value = "name", required = false) String name,
                             @RequestParam(value = "password", required = false) String password,
                             @RequestParam(value = "address", required = false) String address) {
        if (!StringUtil.isEmpty(name)) {
            userService.updateUser(name.trim(), password, address.trim());
        }
        return "user/test";
    }

    @RequestMapping("deleteUser")
    public String deleteUser(@RequestParam(value = "name", required = true) String name) {
        userService.deleteUser(name);
        return "user/test";
    }

    @RequestMapping("queryUser")
    public ModelAndView queryUser(@RequestParam(value = "password", required = false) String password) {
        List<User> userList = userService.queryUser(password);
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName( "user/test" );
        modelAndView.addObject("userList", userList);
        return modelAndView;
    }

    /**
     * 上传头像
     * @param icon
     * @param model
     * @return
     */
    @RequestMapping("upload_img")
    public String upLoadImg(MultipartFile icon, Model model) {
        String url = userService.uploadImg(icon);
        model.addAttribute("imgUrl", url);
        return "user/update_image";
    }


    /**
     * 截取头像
     * @param imgUrl
     * @param x
     * @param y
     * @param width
     * @param height
     * @return
     */
    @RequestMapping("crop_img")
    public String cropImg(String imgUrl, int x, int y, int width, int height, HttpSession session, Model model) {
        User user = (User)session.getAttribute("user");
        String newImgUrl = userService.cropImg(user.getId(), imgUrl, x, y, width, height);
        user.setImgUrl(newImgUrl);
        return getProfile(session, model);
    }

    /**
     * 头像修改页
     * @return
     */
    @RequestMapping("get_user_image")
    public String getUserImage(Model model,  HttpSession session) {
        User user = (User)session.getAttribute("user");
        model.addAttribute("imgUrl", userService.findUser(user.getId()).getImgUrl());
        model.addAttribute("user",  userService.findUser(user.getId()));
        return "user/update_image";
    }

    /**
     * 获得用户简介页面
     * @param uid
     * @param model
     * @param session
     * @return
     */
    @RequestMapping("get_user_info")
    public String getUserInfo(Integer uid, Model model, HttpSession session) {
        User user = userService.findUser(uid);
        model.addAttribute("userInfo", user);
        return "user/user_info";
    }

}
